package numerics;

import statistics.TestTStudentDistribution;


public class TStudentDistribution implements Function {
	int d;

	public TStudentDistribution(int i) {
		d = i;
	}
	
	public class dFunction implements Function {

		@Override
		public double eval(double x) {
			return calcProbabilityDensity(x);
		}
	}

	public double calcProbabilityDensity(double x) {
		
		double numerator = GammaFunction.calcGammaFunction( 
				(d + 1.0) / 2.0 ) * Math.pow((1.0 + Math.pow(x, 2.0) / d), (-(d+1.0)/2.0));
		
		double denominator = (Math.pow((d * Math.PI), 0.5) * GammaFunction.calcGammaFunction(d/2.0));
		
		return numerator / denominator;
	}
	
	
	public double calcPGivenX(double x) {
		if( x == 0 )
			return 0.5;
		else if( x > 0 )
			return 0.5 + SimpsonMethod.calcIntegral(new dFunction(), 0, x, TestTStudentDistribution.MAX_ERROR);
		else
			return 0.5 - SimpsonMethod.calcIntegral(new dFunction(), x, 0, TestTStudentDistribution.MAX_ERROR);
	}

	public double calcXGivenP(double p) {
		return NewtonRapsonMethod.findArgument(this, new dFunction(), p, 0.0, TestTStudentDistribution.MAX_ERROR);
	}
	
	@Override
	public double eval(double x) {
		return calcPGivenX(x);
	}

}
